﻿using System;
using System.Web;
using System.Web.Mvc;

namespace Actya.Web.Mvc.Helpers
{
	public static class MessageExtensions
	{
		public static void ShowMessage(this Controller controller, MessageType messageType, string message, bool showAfterRedirect = false)
		{
			var messageTypeKey = messageType.ToString();
			if (showAfterRedirect)
			{
				controller.TempData[messageTypeKey] = message;
			}
			else
			{
				controller.ViewData[messageTypeKey] = message;
			}
		}

		public static HtmlString DisplayMessages(this CmsHelper cmsHelper)
		{
			var messages = String.Empty;
			foreach (var messageType in Enum.GetNames(typeof (MessageType)))
			{
				var message = cmsHelper.ViewContext.ViewData.ContainsKey(messageType)
				              	? cmsHelper.ViewContext.ViewData[messageType]
				              	: cmsHelper.ViewContext.TempData.ContainsKey(messageType)
				              	  	? cmsHelper.ViewContext.TempData[messageType]
				              	  	: null;
				if (message != null)
				{
					var messageBoxBuilder = new TagBuilder("div");
					messageBoxBuilder.AddCssClass(String.Format("messagebox {0}", messageType.ToLowerInvariant()));
					messageBoxBuilder.SetInnerText(message.ToString());
					messages += messageBoxBuilder.ToString();
				}
			}
			return MvcHtmlString.Create(messages);
		}
	}

	public enum MessageType
	{
		Success,
		Warning,
		Error
	}

}